package com.project651.www;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class StartGameService extends Service {
	public static final String SERVER = ".com.project651.www.StartGameService";
	static final String TAG = "StartGameProcess";
	static public final int BUFFERSIZE = 512;
	static public final int PORT_NUM = 3333;
	
	Thread server;
	private final IBinder mBinder = new StartGameServiceBinder();
	
	private ServerSocket serverSocket;
	private Socket socket;
	private InputStream in;
	private OutputStream out;
	private String clientAddr;
	private int clientPort = -1;
	private boolean isRunning = true;
	
	class StartGameServiceBinder extends Binder {
		public StartGameService getService() {
			return StartGameService.this;
		}
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return mBinder;
	}
	
	public void onCreate() {
		startServer();
		super.onCreate();
	}

	private void startServer() {
		if (server == null) {
			server = new Thread(serverThread);
			server.start();
		} else {
			server = new Thread(serverThread);
			server.start();
			Log.d(TAG, "The connection had to be restarted.");
		}
	}
	
	public void sendWord(CharSequence word) {
		try {	
			out.write(Crypto.encrypt(word));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void closeServerConnection() {
		try {
			if (socket != null) {
				in.close();
				out.close();
				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void closeServer() {
		try {
			if (serverSocket != null) serverSocket.close();
			server = null;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void onReceiveStatus(int status) {
		Intent i = new Intent(SERVER);
		Bundle b = new Bundle();
		b.putInt("Status", status);
		i.putExtras(b);
		sendBroadcast(i);
	}
	
	private void onConnectionAttempt() {
		Intent i = new Intent(SERVER);
		Bundle b = new Bundle();
		//maybe attach the word and send it here as well?
		b.putString("IP", socket.getInetAddress().getHostAddress());
		b.putInt("Port", socket.getPort());
		i.putExtras(b);
		sendBroadcast(i);
	}

	private Runnable serverThread = new Runnable() {

		public void run() {
			try {
				serverSocket = new ServerSocket(PORT_NUM);
				byte[] buffer = new byte[BUFFERSIZE];
				
				while (true) {
					// create the socket
					socket = serverSocket.accept();
					if (clientPort == -1) {
						clientAddr = socket.getInetAddress().getHostAddress();
						clientPort = socket.getPort();
					} else {
						// no connection
						
						break;
					}
					
					//connection has been established
					in = socket.getInputStream();
					out = socket.getOutputStream();
					isRunning = true;
					
					onConnectionAttempt();
					
					while (isRunning) {
						in.read(buffer);
						//at this point the game must be over
						//TODO get the status from the buffer
						int status = buffer[0];
						onReceiveStatus(status);
					}
				}
				
				closeServerConnection();
			} catch (IOException e) {
				e.printStackTrace();
				
				closeServerConnection();
				closeServer();
				startServer();
			}
			
		}
		
	};
}
